#include <sys/types.h>
#include <sys/socket.h>
#include "custom_handle.h"
#include <sys/ipc.h>
#include <sys/msg.h>

#define KB 1024
#define HTML_SIZE (64 * KB)

// 普通的文本回复需要增加html头部
#define HTML_HEAD "Content-Type: text/html\r\n" \
                  "Connection: close\r\n"

static int handle_login(int sock, const char *input)
{
    char reply_buf[HTML_SIZE] = {0};
    char *uname = strstr(input, "username=");
    uname += strlen("username=");
    char *p = strstr(input, "password");
    *(p - 1) = '\0';
    printf("username = %s\n", uname);

    char *passwd = p + strlen("password=");
    printf("passwd = %s\n", passwd);

    if (strcmp(uname, "admin") == 0 && strcmp(passwd, "fzc123") == 0)
    {
        sprintf(reply_buf, "<script>localStorage.setItem('usr_user_name', '%s');</script>", uname);
        strcat(reply_buf, "<script>window.location.href = '/example.html';</script>");
        send(sock, reply_buf, strlen(reply_buf), 0);
    }
    else
    {
        printf("web login failed\n");

        //"用户名或密码错误"提示，chrome浏览器直接输送utf-8字符流乱码，没有找到太好解决方案，先过渡
        char out[128] = {0xd3, 0xc3, 0xbb, 0xa7, 0xc3, 0xfb, 0xbb, 0xf2, 0xc3, 0xdc, 0xc2, 0xeb, 0xb4, 0xed, 0xce, 0xf3};
        sprintf(reply_buf, "<script charset='gb2312'>alert('%s');</script>", out);
        strcat(reply_buf, "<script>window.location.href = '/login.html';</script>");
        send(sock, reply_buf, strlen(reply_buf), 0);
    }

    return 0;
}

// 共享内存获取传感器数据并发送给网页
static int handle_register(int sock, const char *input)
{
    int shmid = shmget(SHM_KEY, sizeof(sensor_data_t), 0666);
    sensor_data_t *pdata = (sensor_data_t *)shmat(shmid, NULL, 0);
    char buf[48] = {0};
    sprintf(buf, "%d,%d", pdata->value1, pdata->value2);
    send(sock, buf, strlen(buf), 0);
    shmdt(pdata);
    return 0;
}

// 消息队列录入led与蜂鸣器状态
static int handle_state(int sock, const char *input)
{
    int msgid = msgget(MSG_KEY, IPC_CREAT | 0666);
    ctrl_msg_t msg;
    msg.mtype = 1; // 消息类型随意，实际不用
    char buf[32] = {0};
    if (strstr(input, "buzzer"))
    {
        if (strstr(input, "on"))
        {
            strcpy(msg.cmd, "buzzer_on");
            buf[0] = '1';
        }
        else if (strstr(input, "off"))
        {
            strcpy(msg.cmd, "buzzer_off");
            buf[0] = '0';
        }
    }
    else if (strstr(input, "led"))
    {
        if (strstr(input, "on"))
        {
            strcpy(msg.cmd, "led_on");
            buf[0] = '1';
        }
        else if (strstr(input, "off"))
        {
            strcpy(msg.cmd, "led_off");
            buf[0] = '0';
        }
    }
    msgsnd(msgid, &msg, sizeof(msg.cmd), 0);
    send(sock, buf, strlen(buf), 0);
    return 0;
}

/**
 * @brief 处理自定义请求，在这里添加进程通信
 * @param input
 * @return
 */
int parse_and_process(int sock, const char *query_string, const char *input)
{
    // query_string不一定能用的到

    // 先处理登录操作
    if (strstr(input, "username=") && strstr(input, "password="))
    {
        return handle_login(sock, input);
    }
    // 处理传感器数据
    else if (strstr(input, "reload"))
    {
        return handle_register(sock, input);
    }
    // 处理蜂鸣器和LED灯状态
    else if (strstr(input, "buzzer") || strstr(input, "led"))
    {
        return handle_state(sock, input);
    }
    else // 剩下的都是json请求，这个和协议有关了
    {
        // 构建要回复的JSON数据
        const char *json_response = "1,2,3,4";

        // 发送HTTP响应给客户端
        send(sock, json_response, strlen(json_response), 0);
    }

    return 0;
}
